﻿#region "Copyright (C) Lenny Granovsky. 2005-2013"
//This program is free software distribute under the terms of the GNU General Public License as published by
//the Free Software Foundation. Please read AssemblyInfo.cs file for more information.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Web.Enhancements.Rest.Templates
{
    /// <summary>
    /// Class that provides ability to return data through REST services that should be 
    /// processed as XML-formatted data to respond back to the client.
    /// </summary>
    internal class XmlTemplate : ITemplatedResult
    {
        /// <summary>
        /// Gets or sets result data that should be returned to the client.
        /// </summary>
        public object ResultData { get; set; }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public XmlTemplate()
        {
        }

        /// <summary>
        /// Contsractor that accpets result data that class should process into XML response.
        /// </summary>
        /// <param name="resultData">Result data as an object</param>
        public XmlTemplate(object resultData)
        {
            this.ResultData = resultData;
        }

        /// <summary>
        /// Method converts ResultData object to XML format and renders content into given HTTP response object.
        /// </summary>
        /// <param name="response">HTTP response object.</param>
        public void RenderResult(System.Web.HttpResponse response)
        {
            XmlSerializer ser = new XmlSerializer(this.ResultData.GetType());
            XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
            xsn.Add("", ""); //to avoid addition of default MS namespaces
            ser.Serialize(response.OutputStream, this.ResultData, xsn);
        }
    }
}
